Yes. This means that a JButton
can contain
other components, usually a little icon (picture).
Ordinary AWT buttons (class Button
) can't do this.
Here is a sample program, nearly the same as the one in the previous chapter, with the addition of a button.
To construct a JButton
object, use
new
, as with all classes.
Now you have a JButton
object,
but you still need to do something with it.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonDemo extends JFrame { JButton bChange ; // reference to the button object // constructor for ButtonDemo ButtonDemo() { // construct a Button bChange = new JButton("Click Me!"); // add the button to the JFrame getContentPane().add( bChange ); } public static void main ( String[] args ) { ButtonDemo frm = new ButtonDemo(); WindowQuitter wquit = new WindowQuitter(); frm.addWindowListener( wquit ); frm.setSize( 200, 150 ); frm.setVisible( true ); } } class WindowQuitter extends WindowAdapter { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } }
This program adds
a JButton
to the frame
when the frame is constructed.
The button (and other GUI components) are added to the frame's content pane. The content pane is a container that represents the main rectangle of the frame.
To get a reference to the content pane, use
the getContentPane()
method of the frame.